﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.Office.Server;
using Microsoft.Office.Server.Search;
using Microsoft.Office.Server.Search.Query;
using System.Data;
using System.Xml;
using Siderys.Blog.Search.Engine.Resultado;

namespace Siderys.Blog.Search.Engine
{
    public class ConsultaSQL
    {
        string mAmbito = string.Empty;
        string mTxtBusqueda = string.Empty;
        FullTextSqlQuery mQueryMossSql = null;
        //example for freetext:
        //FREETEXT('text')
        //FREETEXT(Property, 'text')
        //Sintaxis:
        //"scope"='scope' AND FREETEXT('texto')
        string mQuerySql = "SELECT WorkId, Rank, Title, Author, Size, Path, Description, Write FROM Scope() WHERE";
        ResultTableCollection lResultadoBusqueda = null;

        public ConsultaSQL(string pTxtBusqueda, string pAmbito)
        {
            mAmbito = pAmbito;
            mTxtBusqueda = pTxtBusqueda;
            mQueryMossSql = new FullTextSqlQuery(ServerContext.GetContext("SSPSidmossfa"));
        }

        private string ArmarConsulta()
        {
            string lRetorno = string.Empty;
            if (!mAmbito.Equals(string.Empty))
            {
                lRetorno += " \"scope\"='" + mAmbito + "' AND ";
            }
            lRetorno += "FREETEXT('" + mTxtBusqueda + "')";

            return mQuerySql + lRetorno;
        }

        public List<ObjetoResultado> GetResultadoBusquedaCol()
        {
            List<ObjetoResultado> lRetorno = null;
            //mQueryMossSql.QueryText = "SELECT Title, Path, Rank, Description FROM Scope()";
            mQueryMossSql.QueryText = ArmarConsulta();
            mQueryMossSql.ResultTypes |= ResultType.RelevantResults;
            lResultadoBusqueda = mQueryMossSql.Execute();
            if (lResultadoBusqueda[ResultType.RelevantResults].RowCount > 0)
            {
                lRetorno = Utility.ReturnResultTableToList(lResultadoBusqueda[ResultType.RelevantResults]);
            }
            return lRetorno;
        }
        
    }
}
